<template>
    <div class="app-container">
        <el-row :gutter="0">
            <!--专病数据-->
            <el-form class="formBox formBox1  searchForm" :model="queryParams" ref="queryForm" size="small"
                :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="选择医院">
                    <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="180px"
                        ref="department" :isUserAll="true">
                    </department>
                </el-form-item>
                <el-form-item label="选择时间">
                    <el-date-picker v-model="dateRange" style="width: 190px;margin-right:10px;"
                        :picker-options="pickerOptions" value-format="yyyy-MM-dd" type="daterange" size="mini"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleQuery"
                        :clearable="false"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
                    <el-button icon="el-icon-printer" size="mini" type="success" @click="handleExport">导出</el-button>
                </el-form-item>
            </el-form>
            <div class="formBox searchForm" ref="statisticalTable">
                <el-collapse accordion style="border:none;width:100%;margin-bottom:10px;margin-top:4px;"
                    v-model="PlanactiveName">
                    <!-- :summary-method="getSummaries" -->
                    <el-collapse-item title="顾客登记来源统计表" style="border:none" name="1">
                        <el-table border v-loading="loading" :data="tableLists" show-summary id="out-table" ref="table"
                            :height="statisticalTableH">
                            <!-- obj.dnumber = item.rtList[0].number
                        obj.xhnumber = item.rtList[1].number
                        obj.bynumber = item.rtList[2].number
                        obj.pynumber = item.rtList[3].number
                        obj.qtnumber = item.rtList[4].number
                        obj.wtnumber = item.rtList[5].number
                        obj.dateTime = item.dateTime -->
                            <el-table-column label="月份" align="center" prop="dateTime" :show-overflow-tooltip="true"
                                width="160" fixed>

                            </el-table-column>
                            <el-table-column label="抖音" align="center" prop="dnumber">
                                <template slot-scope="scope">
                                    <span style="color:red;font-weight:700;"
                                        v-if="scope.row.dnumber">{{ scope.row.dnumber }}</span>

                                    <span v-else>--</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="小红书" align="center" prop="xhnumber">
                                <template slot-scope="scope">
                                    <span style="color:red;font-weight:700;"
                                        v-if="scope.row.xhnumber">{{ scope.row.xhnumber }}</span>

                                    <span v-else>--</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="本院" align="center" prop="bynumber">
                                <template slot-scope="scope">
                                    <span style="color:red;font-weight:700;"
                                        v-if="scope.row.bynumber">{{ scope.row.bynumber }}</span>
                                    <span v-else>--</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="朋友推荐" align="center" prop="pynumber">
                                <template slot-scope="scope">
                                    <span style="color:red;font-weight:700;"
                                        v-if="scope.row.pynumber">{{ scope.row.pynumber }}</span>
                                    <span v-else>--</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="其他" align="center" prop="qtnumber">
                                <template slot-scope="scope">
                                    <span style="color:red;font-weight:700;"
                                        v-if="scope.row.qtnumber">{{ scope.row.qtnumber }}</span>
                                    <span v-else>--</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="未填" align="center" prop="wtnumber">
                                <template slot-scope="scope">
                                    <span style="color:red;font-weight:700;"
                                        v-if="scope.row.wtnumber">{{ scope.row.wtnumber }}</span>
                                    <span v-else>--</span>
                                </template>
                            </el-table-column>


                        </el-table>
                    </el-collapse-item>
                </el-collapse>
                <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
            </div>
            <div class="formBox">
                <div class="echart-box">
                    <div id="treatmentAndIncome" style="width:100%;height:500px;cursor:pointer;">
                        <div v-if="tableLists.length == 0">
                            <img class="parent-img" src="@/assets/404_images/404_cloud.png" alt="404">
                            <div class="parent-text"> 暂无统计数据！</div>
                        </div>
                    </div>

                </div>
            </div>


        </el-row>


    </div>
</template>

<script>
//引入安装的依赖
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
import XLSXD from "xlsx-style";
import * as echarts from "echarts";
import department from "@/views/components/department/index.vue";
import { statisticsDdataSource } from "@/api/system/specialCom";
const treatmentAndIncomeOption = {
    title: {
        text: '登记来源统计表',
    },
    // 滚动条
    dataZoom: [
        {
            show: true,
            type: 'slider',
            zoomLock: true,
            // realtime: true,
            // start: 0,
            // end:30,
            startValue: 0,
            endValue: 4,
            xAxisIndex: [0],
            bottom: '0',
            left: '50',
            height: 15,
            borderColor: 'rgba(0,0,0,0)',
            textStyle: {
                color: 'transparent'
            }
        }
    ],
    label: {
        show: true, //开启显示数值
        position: 'top', //数值在上方显示
        textStyle: {  //数值样式
            //color: '#D1DBFF',   //字体颜色
            //fontSize: 14  //字体大小
        }
    },
    toolbox: {
        show: true,
        feature: {
            mark: { show: true },
            // dataView : {show: true, readOnly: false},
            magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
            restore: { show: true },
            saveAsImage: { show: true }
        }
    },
    legend: {
        // Try 'horizontal'
        orient: 'vertical',
        right: 0,
        top: 'center'
    },
    tooltip: {},
    dataset: {
        dimensions: ["dateTime", "抖音", "小红书", '本院', '朋友推荐', '其他', '未填'],
        source: [

        ],
    },
    yAxis: { //xAxis
        nameTextStyle: {
            borderType: "dotted",
            color: 'red',

        }
    },
    grid: {
        bottom: 100
    },
    xAxis: {
        type: "category",
        padding: 10,
        axisLabel: {
            color: "red",
            rotate: 0,
            interval: 0,
            margin: 5,
            fontSize: 14,
            formatter(params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 8;  //一行显示几个字
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                    for (var p = 0; p < rowNumber; p++) {
                        var tempStr = "";
                        var start = p * provideNumber;
                        var end = start + provideNumber;
                        if (p == rowNumber - 1) {
                            tempStr = params.substring(start, paramsNameNumber);
                        } else {
                            tempStr = params.substring(start, end) + "\n";
                        }
                        newParamsName += tempStr;
                    }
                } else {
                    newParamsName = params;
                }
                return newParamsName;
            }
        }
    },
    series: [{ type: "bar", color: "#b6dd09", barWidth: "20" },
    { type: "bar", color: "red", barWidth: "20" },
    { type: "bar", color: "blue", barWidth: "20" },
    { type: "bar", color: "#2cdd09", barWidth: "20" },
    { type: "bar", color: "green", barWidth: "20" },
    { type: "bar", color: "orange", barWidth: "20" }
    ],
};
export default {
    name: "doctorSum",
    dicts: [
        "sys_source_type",
    ],
    components: { department },
    data() {
        return {
            PlanactiveName: '',
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now() - 8.64e6;  //如果没有后面的-8.64e6就是不可以选择今天的
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        const end = date;
                        const start = date;
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '前天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 2);
                        const end = date;
                        const start = date;
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近六个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近1年',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            // 方案表格数据
            tableLists: [],
            planList: [],
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 日期范围
            dateRange: [],
            // 表单参数
            // form: {},
            form: {

            },
            pageNum: 1,
            pageSize: 10,
            statisticalTableH: undefined,
            // 查询参数
            queryParams: {
                // pageNum: 1,
                // pageSize: 10,
                hospitalId: '',
                deptId: '',
            },
        };
    },
    watch: {},
    computed: {
        // 默认查6个月
        defaultTime: function () {//默认从1月1号 到 现在
            let date = new Date();
            let year = date.getFullYear();
            let month0 = date.getMonth() + 1;
          
            let day = date.getDate();
            let month = month0 > 9 ? month0 : "0" + month0;
            day = day < 10 ? "0" + day : day;
            let day0 = '01';
            let today = year + "-" + month + "-" + day;
            let firtsDay = year + "-01-01";
            if (month0 - 3 > 0) {
                firtsDay = year + "-0" + (month0 - 3) + "-01" 
            }
            return [firtsDay, today];
        },
    },
    async created() {

    },
    mounted() {
        this.dateRange = this.defaultTime
        this.changeHeight()

    },
    updated() {
        this.$nextTick(() => {
            this.$refs.table.doLayout()
        })
    },
    methods: {
        getSummaries(param) {
            let that = this
            const { columns, data } = param;
            const sums = [];

            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                // if (index === 1) {
                //     return;
                // }

                console.log(column)

                const values = data.map(item => {
                    return Number(item[column.property])
                });
                console.log(values)
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] += '';
                } else {
                    sums[index] = '';
                }


            });
            return sums;
        },
        changeHeight() {
            if (this.$refs.statisticalTable) {
                const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
                let h = statisticalTableObj.top + 80
                this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
            } else {
                this.statisticalTableH = '500px'
            }
        },
        handleExport() {
            let tables = document.getElementById('out-table').cloneNode(true) // 重点
            if (tables.querySelector(".el-table__fixed")) {
                tables.removeChild(tables.querySelector(".el-table__fixed")) // 重点
            }
            let wb = XLSX.utils.table_to_book(tables, { sheet: '顾客登记来源统计表' })
            this.setExlStyle(wb['Sheets']['顾客登记来源统计表'])
            //合并单元格边框补齐
            this.addRangeBorder(wb['Sheets']['顾客登记来源统计表']['!merges'], wb['Sheets']['顾客登记来源统计表'])
            var ws = XLSXD.write(wb, {
                type: "buffer"
            });
            try {
                FileSaver.saveAs(
                    new Blob([ws], { type: "application/octet-stream" }),
                    `顾客登记来源统计表_${this.dateRange[0]}~${this.dateRange[1]}.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, ws);
            }
            return ws;

        },
        setExlStyle(data) {
            let borderAll = {//单元格外侧框线
                top: {
                    style: 'thin',
                },
                bottom: {
                    style: 'thin'
                },
                left: {
                    style: 'thin'
                },
                right: {
                    style: 'thin'
                }
            };
            data['!cols'] = [];
            for (let key in data) {
                if (data[key] instanceof Object) {
                    data[key].s = {
                        border: borderAll,
                        alignment: {
                            horizontal: 'center',//水平居中对齐
                            vertical: 'center'
                        },
                        font: {
                            sz: 11
                        },
                        bold: true,
                        numFmt: 0
                    }
                    data['!cols'].push({ wpx: 150 });
                }
            }
            return data;
        },
        addRangeBorder(range, ws) {
            let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
            if (range == undefined || range == null) {
                return
            }
            range.forEach(item => {
                let startRowNumber = Number(item.s.c),
                    endRowNumber = Number(item.e.c);
                for (let i = startRowNumber; i <= endRowNumber; i++) {
                    for (let j = Number(item.s.r) + 1; j <= Number(item.e.r); j++) {
                        ws[`${arr[i]}${j + 1}`] = { s: { border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } } } };
                    }
                }
            })
            return ws;
        },
        refreshData(data) {
            console.log(data)
            if (data.hospitalId) {
                this.queryParams.hospitalId = data.hospitalId
                this.queryParams.deptId = data.deptId

                this.getList()
            } else {
                this.queryParams.hospitalId = ''
                this.loading = false
            }
        },
        getList() {
            let that = this
            that.loading = true;
            if (that.queryParams.hospitalId == undefined || that.queryParams.hospitalId == "" || that.queryParams.hospitalId == null) {
                this.$modal.msgError("请选择医院!");
                that.loading = false;
                return false
            }
            let params = {
                startTime: that.dateRange[0],
                endTime: that.dateRange[1],
                ...that.queryParams
            }
            statisticsDdataSource(params).then((response) => {
                if (response.code == 200) {
                    let data = response.data;
                    let voLists = data
                    let voLarr = []
                    //"dateTime", "抖音", "小红书", '本院', '朋友推荐', '其他','未填'
                    voLists.forEach(item => {
                        let obj = {}

                        obj.dnumber = item.rtList[0].number
                        obj.xhnumber = item.rtList[1].number
                        obj.bynumber = item.rtList[2].number
                        obj.pynumber = item.rtList[3].number
                        obj.qtnumber = item.rtList[4].number
                        obj.wtnumber = item.rtList[5].number
                        obj.dateTime = this.getMounthShow(item.dateTime)
                        voLarr.push(obj)
                    })
                    that.tableLists = voLarr
                    var treatmentAndIncomeChart = echarts.init(document.getElementById("treatmentAndIncome"));
                    var a = JSON.stringify(voLarr).replace(/dnumber/g, "抖音").replace(/xhnumber/g, "小红书").replace(/bynumber/g, "本院").replace(/pynumber/g, "朋友推荐").replace(/qtnumber/g, "其他").replace(/wtnumber/g, "未填");

                    treatmentAndIncomeOption.dataset.source = JSON.parse(a)
                    if (voLists.length > 0) {
                        treatmentAndIncomeChart.clear()
                        treatmentAndIncomeChart.setOption(treatmentAndIncomeOption);
                    } else {
                        treatmentAndIncomeChart.clear()
                        treatmentAndIncomeChart.setOption({
                            title: {
                                text: '暂无统计数据!',
                                x: 'center',
                                y: 'center',
                                textStyle: {
                                    fontSize: 16,
                                    color: '#909399',
                                    fontWeight: 'normal'
                                }
                            }
                        })
                    }
                }
                that.loading = false;
            });

        },
        getMounthShow(dateTime) {
            if (dateTime) {
                let arr = dateTime.split('-')
                return arr[0] + '年' + arr[1] + '月'
            }
        },
        // 真实序号计算（计算分页影响）
        getIndex(index) {
            return (this.pageNum - 1) * this.pageNum + index + 1;
        },

        // 取消按钮
        cancel() {

        },
        // 表单重置
        reset() {

        },
        /** 搜索按钮操作 */
        handleQuery() {
            // this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            if (this.$refs.department) {
                this.$refs.department.reset()
            }
        },
    },
};
</script>
<style scoped lang="scss">
::v-deep .statisticalTable .el-table .cell {
    font-size: 12px;
}

.echart-box {
    cursor: pointer;
    margin-top: 20px;
}

.parent-img {
    width: 200px;
    height: 200px;
    display: block;
    margin: 10px auto;
}

.parent-text {
    color: #999;
    text-align: center;
}
</style>
